import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getUserInfo, getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  next()
  NProgress.done()

  // determine whether the user has logged in
  // const hasToken = getToken()
  // const hasUserInfo = getUserInfo()
  // // const hasToken = true
  // if (hasToken && hasUserInfo) {
  //   if (to.path === '/login') {
  //     next({ path: '/' })
  //     NProgress.done()
  //   } else {
  //     const getRouters = store.getters.permission_routes && store.getters.permission_routes.length > 0
  //     if (getRouters) {
  //       next()
  //     } else {
  //       try {
  //         const accessRoutes = await store.dispatch('permission/generateRoutes', hasUserInfo)
  //         router.addRoutes(accessRoutes)
  //         if (to.path.indexOf('404') >= 0) {
  //           for (const item of accessRoutes) {
  //             if (item.home) {
  //               next(item.path)
  //               return
  //             }
  //           }
  //         } else {
  //           next({ ...to, replace: true })
  //         }
  //       } catch (err) {
  //         await store.dispatch('user/resetToken')
  //         Message.error(err || 'Has Error')
  //         next(`/login?redirect=${to.path}`)
  //         NProgress.done()
  //       }
  //     }
  //   }
  // } else {
  //   if (whiteList.indexOf(to.path) !== -1) {
  //     next()
  //   } else {
  //     next(`/login?redirect=${to.path}`)
  //     NProgress.done()
  //   }
  // }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
